package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod; // 确保是正确的导入包
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 先判断是否为“无需token的接口”，直接放行（双重保险）
        String requestUri = request.getRequestURI();
        if ("/user/user/login".equals(requestUri) || "/user/shop/status".equals(requestUri)) {
            log.info("无需token接口，直接放行：{}", requestUri);
            return true;
        }

        // 2. 判断是否为Controller方法（非Controller方法如静态资源，直接放行）
        if (!(handler instanceof HandlerMethod)) {
            log.info("非Controller方法，直接放行：{}", requestUri);
            return true;
        }

        // 3. 获取请求头中的token
        String token = request.getHeader(jwtProperties.getUserTokenName());
        // 安全打印token日志：避免空token截取异常
        String tokenLog = (token == null || token.isEmpty()) ? "null" : (token.substring(0, Math.min(token.length(), 10)) + "...");
        log.info("从请求头[{}]获取到token：{}，当前请求路径：{}",
                jwtProperties.getUserTokenName(), tokenLog, requestUri);

        try {
            // 4. 解析token（若token为空，会进入catch块）
            if (token == null || token.isEmpty()) {
                throw new RuntimeException("token为空");
            }
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("token解析成功，当前用户ID：{}", userId);

            // 5. 存入BaseContext
            BaseContext.setCurrentId(userId);
            return true;

        } catch (Exception e) {
            // 6. 解析失败（token为空、过期、签名错误等），返回401
            log.error("token校验失败，原因：{}", e.getMessage());
            response.setStatus(401);
            return false;
        }
    }
}